<template>
  <view class="pass">
    <u-form :model="form" ref="uForm" label-width="228rpx">
      <u-form-item label="昵称" prop="name">
        <u-input disabled v-model="form.name" />
      </u-form-item>
      <u-form-item label="原密码" prop="password">
        <u-input type="password" v-model="form.password" />
      </u-form-item>
      <u-form-item label="新密码" prop="newPassword">
        <u-input type="password" v-model="form.newPassword" />
      </u-form-item>
      <u-form-item label="确认新密码" prop="newPasswordCopy">
        <u-input type="password" v-model="form.newPasswordCopy" />
      </u-form-item>
    </u-form>
    <u-button type="primary" :customStyle="{ height: '90rpx', marginTop: '100rpx' }" @click="submit">确定</u-button>
  </view>
</template>

<script>
import { userModify } from '@/api/user'
import store from '@/store'
export default {
  data() {
    return {
      form: {
        name: '',
        password: '',
        newPassword: '',
        newPasswordCopy: ''
      },
      rules: {
        password: [{
          required: true,
          message: '请输入原密码',
          // 可以单个或者同时写两个触发验证方式
          trigger: ['change', 'blur'],
        }],
        newPassword: [{
          required: true,
          message: '请输入新密码',
          // 可以单个或者同时写两个触发验证方式
          trigger: ['change', 'blur'],
        }, {
          pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/,
          transform(value) {
            return String(value);
          },
          message: '密码长度6-16位，必须包含字母和数字！',
          trigger: ['change', 'blur'],
        }],
        newPasswordCopy: [{
          // 自定义验证函数，见上说明
          validator: (rule, value, callback) => {
            // 上面有说，返回true表示校验通过，返回false表示不通过
            // this.$u.test.mobile()就是返回true或者false的
            if(this.form.newPassword === value){
              callback()
            }
            return this.$u.test.mobile(value)
          },
          message: '请输入正确新密码',
          // 可以单个或者同时写两个触发验证方式
          trigger: ['change', 'blur']
        }],
      }
    }
  },
  computed: {
    userInfo() {
      return store.getters.userInfo
    }
  },
  onLoad() {
    this.form.name = this.userInfo.nickName
  },
  methods: {
    submit() {
      this.$refs.uForm.validate(valid => {
        if (valid) {
          delete this.form.name
          delete this.form.newPasswordCopy
          userModify({
            ...this.form
          }).then(() => {
            this.$toast('修改成功，请重新登录！')
            setTimeout(() => {
              this.$navTo('pages/login/index', {}, 'redirectTo')
            }, 500)
          }).catch(() => {})
        } else {
          console.log('验证失败')
        }
      });
    }
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  }
}
</script>

<style lang="scss">
.pass {
  padding: 32rpx;
}
</style>
